<?php

namespace app\shop\controller\product;

use app\shop\model\product\Product as ProductModel;
use app\shop\model\product\Category as CategoryModel;
use app\shop\service\ProductService;
use app\shop\controller\Controller;
use think\facade\Db;

/**
 * 商品管理控制器
 */
class Product extends Controller
{
    /**
     * 商品列表(全部)
     */
    public function index()
    {
        // 获取全部商品列表
        $model = new ProductModel;
        $list = $model->getList(array_merge(['status' => -1], $this->postData()));
        // 商品分类
        $category = CategoryModel::getCacheTree();
        // 数量
        $product_count = [
            'sell' => $model->getCount('sell'),
            'recovery' => $model->getCount('recovery'),
            'lower' => $model->getCount('lower'),
            'audit' => $model->getCount('audit'),
            'no_audit' => $model->getCount('no_audit')
        ];
        return $this->renderSuccess('', compact('list', 'category', 'product_count'));
    }
	
	public function addProductPlun(){
		$data = json_decode($this->postData()['params'],true);
	
		  $data['time'] = time();
		  $data['province_name'] = strtotime($data['province_name']);
		  
		  
		  
        $id = Db::name('yonghu_pingjia')->insertGetId($data);
        if ($id) {
            return $this->renderSuccess('添加成功', ['id' => $id]);
        } else {
            return $this->renderError('添加失败');
        }
	}
	  
    public function addProductPlunList()
    {
        try {
            // 获取查询参数
            $params = $this->postData();
            $page = isset($params['page']) ? intval($params['page']) : 1;
            $limit = isset($params['limit']) ? intval($params['limit']) : 20;
            $search = isset($params['search']) ? trim($params['search']) : '';
            $where[] = '';
            // 构建查询条件
            $where = [];
            if (!empty($search)) {
                $where[] = ['hot_name', 'like', '%' . $search . '%'];
            }
           
        
			
            // 获取总数
          $total= Db::name('yonghu_pingjia')->where($where)->count();
            
            // 获取列表数据
            $list = Db::name('yonghu_pingjia')
                ->where($where)
                ->order('time desc')
                ->page($page, $limit)
                ->select();
            
       
            $formattedList = [];
            foreach ($list as $key => $item) {
                $formattedList[] = [
                    'idd' => $key+1,
                    'id' => $item['id'] ?? 0,
                     'time' => date('Y-m-d H:i:s', $item['time']),
                    'hot_name' => $item['hot_name'] ?? '',
                    'full_address' => $item['full_address'] ?? '',
                    'province_name' =>date('Y-m-d H:i:s', $item['province_name']),
                    'city_name' => $item['city_name'] ?? '',
                    'district_name' => $item['district_name']
                ];
            }
            
            return $this->renderSuccess('获取成功', [
                'list' => $formattedList,
                'total' => $total,
                'page' => $page,
                'limit' => $limit
            ]);
            
        } catch (\Exception $e) {
            error_log('获取热门设置列表错误: ' . $e->getMessage());
            return $this->renderError('获取列表失败: ' . $e->getMessage());
        }
    }
	  public function remengdeletedd()
    {
        try {
            // 获取POST数据
            $postData = $this->postData();
            
            // 验证必要参数
            if (empty($postData['id'])) {
                return $this->renderError('记录ID不能为空');
            }
            
            $id = intval($postData['id']);
            
            $record = Db::name('yonghu_pingjia')->where('id', $id)->find();
            if (!$record) {
                return $this->renderError('记录不存在');
            }
            
            // 执行删除操作
            $result = Db::name('yonghu_pingjia')->where('id', $id)->delete();
            
            if ($result) {
                
                return $this->renderSuccess('删除成功');
            } else {
                return $this->renderError('删除失败');
            }
            
        } catch (\Exception $e) {
            error_log('删除热门设置记录错误: ' . $e->getMessage());
            return $this->renderError('删除失败: ' . $e->getMessage());
        }
    }
	
	 public function addRengongguiji()
    {
        $data = $this->postData();
        if (empty($data['name'])) {
            return $this->renderError('轨迹名称不能为空');
        }
		
		
        $insert = [
            'guijiForm' => $data['name'],
            'create_time' => time(),
            'dingdn_id' => $data['order_id'],
        ];
        $id = Db::name('rengongguiji')->insertGetId($insert);
        if ($id) {
            return $this->renderSuccess('添加成功', ['id' => $id]);
        } else {
            return $this->renderError('添加失败');
        }
    }

    /**
     * 设置目的地轨迹
     * @return void
     */
    public function setDestination()
    {
        $data = $this->postData();
        if (empty($data['name'])) {
            return $this->renderError('轨迹名称不能为空');
        }
        if (empty($data['time'])) {
            return $this->renderError('轨迹时间不能为空');
        }
        $order_id = $data['order_id'];
        $order = Db::name('order')->where('order_id', $order_id)->find();
        if (!$order){
            return $this->renderError('订单不存在');
        }
        // 先判断是否有生成轨迹
        $row = Db::name('rengongguiji')->where('dingdn_id', $order_id)->find();
        if (empty($row)) {
            return $this->renderError('不存在轨迹');
        }
        $createTime = strtotime($row['create_time']);

        // 大于目的地的轨迹隐藏起来
        Db::name('rengongguiji')->where('dingdn_id', $order_id)->where('create_time','<',$createTime)->update(['status' => 1]);
        Db::name('rengongguiji')->where('dingdn_id', $order_id)->where('create_time','>',$createTime)->update(['status' => 0]);
        Db::name('rengongguiji')->insert([
            'guijiForm' => $data['name'],
            'dingdn_id' =>$order_id,
            'create_time' => strtotime($data['time']),
            'status' => 1,
            'index' =>  99
        ]);
        return $this->renderSuccess('ok');

    }

    public function autoAddRengongguiji()
    {
        $order_id = $this->postData('order_id')[0];
        if (empty($order_id)) {
            return $this->renderError('订单ID不能为空');
        }

        $row = Db::name('rengongguiji')->where('dingdn_id', $order_id)->find();
        if (!empty($row)) {
            return $this->renderError('已存在轨迹');
        }
        $order = Db::name('order')->where('order_id', $order_id)->find();
        if (empty($order)) {
            return $this->renderError('订单不存在');
        }
        Db::name('order')->where('order_id', $order_id)->update(['delivery_status' => 20]);
        $order_address = Db::name('jiedan_order')->where('id', $order['ding_id'])->find();
        $citysList = (new \RouteCity())->between($order_address['kaishidizhi'], $order_address['jishudizhi']);
        $insert_data = [];
        $time = time();
        // 去除最后一个元素
        array_pop($citysList);
        foreach ($citysList as $index => $city) {
            if ($index == 0){
                $time = $time;
            }else{
                $randtime = rand(56400,86400);
                $time += $randtime;
            }

            $insert_data[] = [
                'guijiForm' => '已到' . $city . '节点',
                'dingdn_id' => $order_id,
                'create_time' => $time,
                'status' => $index == 0 ? 1 : 0,
                'index' =>  $index + 1
            ];
        }
        Db::name('rengongguiji')->insertAll($insert_data);
        return $this->renderSuccess('添加成功');
    }

    /**
     * 获取人工轨迹列表
     */
    public function listRengongguiji()
    {
		$list1=[];
        $list = Db::name('rengongguiji')->where(["dingdn_id"=>$this->postData('order_id')])->order('create_time asc')->select();
		
		if($list){
 foreach ($list as $key => $item) {
                 $list1[$key]['create_time']=  date('Y-m-d H:i:s', $item['create_time']);
                 $list1[$key]['guijiForm']=  $item['guijiForm'];
                 $list1[$key]['index']=  $item['index'];
                 $list1[$key]['status']=  $item['status'];
               
            }
		}
        return $this->renderSuccess('ok', ['list' => $list1]);
    }
  /**
     * 接收地址选择数据
     */
    public function remengadd()
    {
        try {
            // 获取POST数据
            $postData = $this->postData();
            
            // 验证必要参数
            if (empty($postData['fullAddress'])) {
                return $this->renderError('地址信息不能为空');
				
            }
           
            // 获取地址信息  $district
            $fullAddress = $postData['fullAddress'];
            $province = isset($postData['province']) ? $postData['province']['name']  : null;
            $city = isset($postData['city']) ? $postData['city']['name']  : null;
            $district = isset($postData['district']) ? $postData['district']['name'] : null;
            $hotName = isset($postData['hotName']) ? $postData['hotName'] : null;  
            
			
			if(Db::name('remeng_list')->where('district', $district)->find()){
			 return $this->renderError('此地址已存在');	
			}
            // 记录日志
            $logData = [
                'fullAddress' => $fullAddress,
                'province' => $province,
                'city' => $city,
                'district' => $district,
                'hotName' => $hotName,
                'create_time' => time(),
                'ip' => $this->request->ip()
            ];
             // dump($logData);
			// exit;
            // 这里可以添加数据库操作，将地址信息保存到数据库
            // 示例：保存到地址表
            /*
            $addressModel = new AddressModel();
            $result = $addressModel->add([
                'full_address' => $fullAddress,
                'province_id' => $province['id'] ?? 0,
                'province_name' => $province['name'] ?? '',
                'city_id' => $city['id'] ?? 0,
                'city_name' => $city['name'] ?? '',
                'district_id' => $district['id'] ?? 0,
                'district_name' => $district['name'] ?? '',
                'create_time' => time()
            ]);
            */
			// se table or view not found: 1146 Table 'kuaiyun.jjjshop_remeng_list' doesn't exis
            Db::name('remeng_list')->insert($logData);
            // 返回成功响应
           return $this->renderSuccess('添加成功');
            
        } catch (\Exception $e) {
            // 记录错误日志
            error_log('地址提交错误: ' . $e->getMessage());
            return $this->renderError('地址提交失败: ' . $e->getMessage());
        }
    }  /**
     * 获取热门设置记录详情  Cannot instantiate abstract class think\Model
     */
    public function remengdetail()
    {
        try {
            // 获取POST数据
            $postData = $this->postData();
            
            // 验证必要参数
            if (empty($postData['id'])) {
                return $this->renderError('记录ID不能为空');
            }
            
            $id = intval($postData['id']);
            
            
            $record = Db::name('remeng_list')->where('id', $id)->find();
            if (!$record) {
                return $this->renderError('记录不存在');
            }
            
            // 格式化数据
            $formattedRecord = [
                'id' => $record['id'] ?? 0,
                'full_address' => $record['fullAddress'] ?? '',
                'province' => $record['province'] ?? 0,
                'city_name' => $record['city'] ?? '',
                'district_name' => $record['district'] ?? '',
                'create_time' => isset($record['create_time']) ? date('Y-m-d H:i:s', $record['create_time']) : '',
            ];
            
            return $this->renderSuccess('获取成功', $formattedRecord);
            
        } catch (\Exception $e) {
            error_log('获取热门设置记录详情错误: ' . $e->getMessage());
            return $this->renderError('获取详情失败: ' . $e->getMessage());
        }
    }
 /**
     * 获取热门设置列表
     */
    public function remenglist()
    {
        try {
            // 获取查询参数
            $params = $this->postData();
            $page = isset($params['page']) ? intval($params['page']) : 1;
            $limit = isset($params['limit']) ? intval($params['limit']) : 20;
            $search = isset($params['search']) ? trim($params['search']) : '';
            $where[] = '';
            // 构建查询条件
            $where = [];
            if (!empty($search)) {
                $where[] = ['fullAddress', 'like', '%' . $search . '%'];
            }
           
            if($params['hotType'] != "全部"){
				
		
				
				 $where[] = ['hotName', '=',  trim($params['hotType'])];
			}
			
            // 获取总数
          $total= Db::name('remeng_list')->where($where)->count();
            
            // 获取列表数据
            $list = Db::name('remeng_list')
                ->where($where)
                ->order('create_time desc')
                ->page($page, $limit)
                ->select();
            
            // 格式化数据
            $formattedList = [];
            foreach ($list as $key => $item) {
                $formattedList[] = [
                    'idd' => $key+1,
                    'id' => $item['id'] ?? 0,
                    'hot_name' => $item['hotName'],
                    'full_address' => $item['fullAddress'] ?? '',
                    'province_name' => $item['province'] ?? '',
                    'city_name' => $item['city'] ?? '',
                    'district_name' => $item['district'] ?? '',
                    'create_time' => isset($item['create_time']) ? date('Y-m-d H:i:s', $item['create_time']) : '',
                ];
            }
            
            return $this->renderSuccess('获取成功', [
                'list' => $formattedList,
                'total' => $total,
                'page' => $page,
                'limit' => $limit
            ]);
            
        } catch (\Exception $e) {
            error_log('获取热门设置列表错误: ' . $e->getMessage());
            return $this->renderError('获取列表失败: ' . $e->getMessage());
        }
    }
	
	  /**
     * 删除热门设置记录
     */
    public function remengdelete()
    {
        try {
            // 获取POST数据
            $postData = $this->postData();
            
            // 验证必要参数
            if (empty($postData['id'])) {
                return $this->renderError('记录ID不能为空');
            }
            
            $id = intval($postData['id']);
            
            $record = Db::name('remeng_list')->where('id', $id)->find();
            if (!$record) {
                return $this->renderError('记录不存在');
            }
            
            // 执行删除操作
            $result = Db::name('remeng_list')->where('id', $id)->delete();
            
            if ($result) {
                
                return $this->renderSuccess('删除成功');
            } else {
                return $this->renderError('删除失败');
            }
            
        } catch (\Exception $e) {
            error_log('删除热门设置记录错误: ' . $e->getMessage());
            return $this->renderError('删除失败: ' . $e->getMessage());
        }
    }
    /**
     * 商品列表(在售)
     */
    public function lists()
    {
        // 获取全部商品列表
        $model = new ProductModel;
        $list = $model->getLists($this->postData());
        // 商品分类
        $catgory = CategoryModel::getCacheTree();
        return $this->renderSuccess('', compact('list', 'catgory'));
    }

    /**
     * 添加商品
     */
    public function add($scene = 'add')
    {
        // get请求
        if($this->request->isGet()){
            return $this->getBaseData();
        }
        //post请求
        $data = json_decode($this->postData()['params'], true);
        if($scene == 'copy'){
            unset($data['create_time']);
            unset($data['sku']['product_sku_id']);
            unset($data['sku']['product_id']);
            unset($data['product_sku']['product_sku_id']);
            unset($data['product_sku']['product_id']);
            if($data['spec_type'] == 20){
                foreach ($data['spec_many']['spec_list'] as &$spec){
                    $spec['product_sku_id'] = 0;
                }
            }
            //初始化销量等数据
            $data['sales_initial'] = 0;
        }

        $model = new ProductModel;
        if (isset($data['product_id'])) {
            $data['product_id'] = 0;
        }

        if ($model->add($data)) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 获取基础数据
     */
    public function getBaseData()
    {
        return $this->renderSuccess('', array_merge(ProductService::getEditData(null, 'add'), []));
    }

    /**
     * 获取编辑数据
     */
    public function getEditData($product_id, $scene = 'edit')
    {
        $model = ProductModel::detail($product_id);
        return $this->renderSuccess('', array_merge(ProductService::getEditData($model, $scene), compact('model')));
    }

    /**
     * 商品编辑
     */
    public function edit($product_id, $scene = 'edit')
    {
        if($this->request->isGet()){
            $model = ProductModel::detail($product_id);
            return $this->renderSuccess('', array_merge(ProductService::getEditData($model, $scene), compact('model')));
        }
        if ($scene == 'copy') {
            return $this->add($scene);
        }
        // 商品详情
        $model = ProductModel::detail($product_id);
        // 更新记录
        if ($model->edit(json_decode($this->postData()['params'], true))) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 修改商品状态
     */
    public function state($product_id, $state)
    {
        // 商品详情
        $model = ProductModel::detail($product_id);
        if (!$model->setStatus($state)) {
            return $this->renderError('操作失败');
        }
        return $this->renderSuccess('操作成功');
    }

    /**
     * 强制下架、再上架
     */
    public function audit($product_id, $state)
    {
        // 商品详情
        $model = ProductModel::detail($product_id);
        if (!$model->setAudit($state)) {
            return $this->renderError('操作失败');
        }
        return $this->renderSuccess('操作成功');
    }
    /**
     * 删除商品
     */
    public function delete($product_id)
    {
        // 商品详情
        $model = ProductModel::detail($product_id);
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

}
